import java.util.Objects;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 07 - 25
 * Time: 9:14
 */
//key-value模型
class Person {
    public String id;
    public Person(String id) {
        this.id = id;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return Objects.equals(id, person.id);
    }
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}
public class HashBucket<K, V> {
    private static class Node<K, V> {
        private K key;
        private V val;
        Node next;
        public Node(K key, V value) {
            this.key = key;
            this.val = value;
        }
    }

    private Node<K, V>[] array;
    private int usedSize;
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public HashBucket() {
        array = (Node<K, V>[])new Node[10];
    }

    public void put(K key, V val) {
        int hash = key.hashCode();
        int index = hash % array.length;
        Node<K, V> cur = array[index];
        while(cur != null) {
            if(cur.key.equals(key)) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        Node<K, V> node = new Node<>(key, val);
        //头插法
        node.next = array[index];
        array[index] = node;
        usedSize++;
        if(loadFactor() >= LOAD_FACTOR) {
            resize();
        }
    }

    //扩容要把所有的元素重新进行哈希
    private void resize() {
        Node<K, V>[] tmpArr = new Node[array.length * 2];
        //遍历原来数组，将原来数组的元素重新哈希到新的数组当中。因为要遍历原来的数组，所以扩容时要申请一个新的数组
        for (int i = 0; i < array.length; i++) {
            Node<K, V> cur = array[i];
            while(cur != null) {
                Node<K, V> curNext = cur.next;
                int hash = cur.key.hashCode();
                int newIndex = hash % array.length;
                //头插法
                cur.next = tmpArr[newIndex];
                tmpArr[newIndex] = cur;
                cur = curNext;
            }
        }
        array = tmpArr;
    }

    private double loadFactor() {
        return usedSize * 1.0 / array.length;//散列表的载荷因子=填入表中的元素个数/散列表的长度
    }

    public V get(K key) {
        int hash = key.hashCode();
        int index = hash % array.length;
        Node<K, V> cur = array[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                return cur.val;
            }
        }
        return null;
    }
}
